package org.gazzax.labs.solrwithmarc.index.processors;

import static org.gazzax.labs.solrwithmarc.index.Utility.isNotNullOrEmptyString;

import java.io.IOException;

import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.processor.UpdateRequestProcessor;
import org.apache.solr.update.processor.UpdateRequestProcessorFactory;

/**
 * Factory for system UID generator.
 * In case your system is indexing bibliographic records coming from different sources,
 * the {@link UpdateRequestProcessor} created by this factory generates a system wide uid.
 */
public class OrganizationAwareIdGeneratorFactory extends UpdateRequestProcessorFactory 
{
	class OrganizationAwareIdGenerator extends UpdateRequestProcessor 
	{	
		OrganizationAwareIdGenerator(final UpdateRequestProcessor next) 
		{
			super(next);
		}
		
		@Override
		public void processAdd(final AddUpdateCommand cmd) throws IOException 
		{
			SolrInputDocument document = cmd.getSolrInputDocument();
			String _003 = (String) document.getFieldValue("003");
			String _001 = (String) document.getFieldValue("001");
			
			if (isNotNullOrEmptyString(_001) && isNotNullOrEmptyString(_003))
			{
				document.setField("001", new StringBuilder(_003).append(_001).toString());
			}

			super.processAdd(cmd);
		}
	}
	
	@Override
	public UpdateRequestProcessor getInstance(
			final SolrQueryRequest request, 
			final SolrQueryResponse response, 
			final UpdateRequestProcessor next) 
	{
		return new OrganizationAwareIdGenerator(next); 
	}
}